<template>
  <div class="brand-con table-gl-w">
    <TableWrap @refresh="getList">
      <template #headerLeft>
        <a-button type="primary" size="medium" class="btn" @click="show('add')">新增</a-button>
        <a-button size="medium" class="gray-outline" style="margin: 0 10px">导入新增类目</a-button>
        <a-button size="medium" class="gray-outline">导出</a-button>
      </template>
      <template #tableBody>
        <a-table size="mini" class="table-singe-line show-border-table" :scroll="{ y: '100%' }" row-key="id" @expand="(e) => expandedKeys.push(e)" v-model:expandedKeys="expandedKeys" :loading="loading" :columns="columns" :pagination="false" :data="data" :style="{ width: '100%' }">
          <template #columns>
            <a-table-column :body-cell-class="tableFirstTdClass" :body-cell-style="tableTdStyleMethod" :data-key="item.level" v-for="item of columns" :key="item.id" :align="item.align" :width="item.width" :title="item.title" :data-index="item.dataIndex">
              <template v-if="item.title === '状态'" #cell="{ record }"> <a-switch v-model="record.status" @change="editStatus($event, record)" /> </template>
              <template v-else-if="item.title === '操作'" #cell="{ record }">
                <div>
                  <a-button v-if="record.level != 3" style="margin-right: 10px" type="text" @click="show('addSub', record)">添加下级</a-button>
                  <a-button style="margin-right: 10px" type="text" @click="show('edit', record)">编辑</a-button>
                  <a-button type="text" style="color: red" @click="del(record)">删除</a-button>
                </div>
              </template>
            </a-table-column>
          </template>
        </a-table>
      </template>
    </TableWrap>
  </div>

  <Detail ref="modelEl" :categoryList="data" :detail="detail" @save="getList" />
</template>

<script lang="ts">
  import { defineComponent, ref, onMounted } from 'vue'
  import Detail from './components/detail.vue'
  import TableWrap from '@/components/TableWrap.vue'
  import { getCategoryList, deleteCategoryList, updateCategoryStatus } from '@/api/product'
  import Sortable from 'sortablejs'
  import { Modal, Message } from '@arco-design/web-vue'

  export default defineComponent({
    name: 'CategoryIndex',
    components: { Detail, TableWrap },
    setup() {
      const loading = ref(false)
      const activeRows = ref([])
      const treeParent = (treeData: any, childKey: any) => {
        const arr: any = []
        const expanded = (data: any) => {
          if (data && data.length > 0) {
            data
              .filter((d: any) => d)
              .forEach((e: any) => {
                arr.push(e)
                expanded(e[childKey] || [])
              })
          }
        }
        expanded(treeData)
        return arr
      }

      const rowDrop = () => {
        const tbody: any = document.querySelector('.arco-table-element tbody')
        Sortable.create(tbody, {
          animation: 200, // 定义排序动画的时间
          forceFallback: true,
          onEnd(event) {
            // console.log(event)
          },
          onChoose(event) {
            // console.log(event)
          },
          onMove: (data, data1) => {
            console.log(data, data1, '222')
            // return false

            // console.log(data.dragged, data.related)
            // const oldRow = data.value[dragged.rowIndex] // 移动的那个元素
            // const newRow = data.value[related.rowIndex] // 新的元素
            // if (oldRow.parentId !== newRow.parentId) {
            //   // 移动的元素与新元素父级id不相同
            //   return false // 不允许跨级拖动
            // }
          },
          onStart: () => {
            // activeRows.value = treeParent(data.value, 'children')
            // console.log(activeRows.value)
          },
        })
      }
      const expandedKeys = ref<any>([])
      const columns: any = [
        {
          title: '类目名称',
          dataIndex: 'name',
          align: 'left',
          width: 250,
        },
        {
          title: '类目编号',
          dataIndex: 'code',
          align: 'left',
          width: 200,
        },
        {
          title: '状态',
          dataIndex: 'status',
          align: 'left',
          width: 200,
        },
        {
          title: '操作',
          dataIndex: 'email',
          align: 'left',
          width: 100,
        },
      ]
      let data = ref([])

      const modelEl = ref()

      const detail = ref({ type: '', data: null })
      const show = (type: string, data?: any) => {
        detail.value.type = type
        data ? (detail.value.data = data) : (detail.value.data = null)
        modelEl.value.visible = true
      }

      const editStatus = async (status: any, data: any) => {
        let params: any = {
          status: status,
          idList: new Array(data.id),
        }
        const res: any = await updateCategoryStatus(params)
        if ((res.code = 'SUCCESS')) {
          Message.success('修改成功')
        }
        getList()
      }

      const del = (data: any) => {
        let params = {
          idList: new Array(data.id),
        }
        Modal.error({
          title: '删除确认',
          content: '信息删除后无法恢复，确定要删除吗？',
          titleAlign: 'start',
          cancelText: '取消',
          hideCancel: false,
          onBeforeOk: async (done) => {
            const res: any = await deleteCategoryList(params)
            if (res.code == 'SUCCESS') {
              done(true)
              Message.success('删除成功')
              getList()
            }
          },
        })
      }

      const getList = async () => {
        let params = {}
        loading.value = true
        const res: any = await getCategoryList(params)
        if (res.code == 'SUCCESS') {
          data.value = res.data
        }
        loading.value = false
      }

      const tableTdStyleMethod = (record: any) => {
        if (record.level == 2 || record.level == 3) {
          return {
            backgroundColor: '#f2f2f2',
            position: 'relative',
          }
        }
      }

      const tableFirstTdClass = (record: any) => {
        if (record.level == 3) {
          return 'third-style'
        }
      }

      getList()

      // onMounted(() => rowDrop())
      // const tableChange = (data: any, extra: any, currentData: any) => {
      //   console.log(data, extra, currentData)
      // }

      return {
        loading,
        expandedKeys,
        columns,
        data,
        editStatus,
        modelEl,
        show,
        detail,
        del,
        getList,
        tableTdStyleMethod,
        tableFirstTdClass,
        // tableChange,
      }
    },
  })
</script>

<style lang="less" scoped>
  :deep(.third-style) {
    &::before {
      position: absolute;
      top: 46px;
      left: 0;
      display: inline-block;
      width: 60px;
      // height: 60px;
      content: '';
      background-color: #f2f2f2;
      z-index: 10;
      border: 1px solid #f2f2f2;
    }
  }

  :deep(.arco-table-tr) {
    td {
      &::before {
        display: none;
      }
      &:nth-child(1) {
        &::before {
          display: block;
        }
      }
    }
  }

  .brand-con {
    background: white;
    // border-radius: 10px;
    width: 100%;

    .header {
      height: 40px;
      line-height: 40px;
      padding: 0 20px;
      box-sizing: border-box;
      border-bottom: 1px solid #ddd;
    }

    .table-con {
      padding: 10px 20px;
      box-sizing: border-box;
      // height: cals;
    }
  }
</style>
